package com.caiden_micheal.user.scheduled;

import com.caiden_micheal.base.properties.TimedTasksProperties;
import com.caiden_micheal.user.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Service
public class UserScheduledTaskService implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(UserScheduledTaskService.class);

    @Autowired
    private TimedTasksProperties timedTasksProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
        taskRegistrar.addTriggerTask(
                () -> {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.MINUTE, timedTasksProperties.getUserDuration());
                    userMapper.deleteDeActiveUser((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(calendar.getTime()));
                    logger.info("UserScheduledTaskService Timed task execution completed!");
                },
                triggerContext -> new CronTrigger(timedTasksProperties.getUserRegisterClear()).nextExecutionTime(triggerContext)
        );
    }

    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(5);
    }
}